<template>
  <div style="padding: 20px">
    <input ref="xml-upload-input" class="xml-upload-input" type="file" accept=".xml" @change="handleClick">
    <div class="drop" @drop="handleDrop" @dragover="handleDragover" @dragenter="handleDragover">
      请拖入XML格式文件
      <el-button :loading="loading" style="margin-left:16px;" size="mini" type="primary" @click="handleUpload">
        浏览...
      </el-button>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    beforeUpload: Function, // eslint-disable-line
    onSuccess: Function// eslint-disable-line
  },
  data() {
    return {
      loading: false,
      exportData: null
    }
  },
  methods: {
    generateData(e) {
      this.exportData = e
      this.onSuccess && this.onSuccess(this.exportData)
    },
    handleDrop(e) {
      e.stopPropagation()
      e.preventDefault()
      if (this.loading) return
      const files = e.dataTransfer.files
      if (files.length !== 1) {
        this.$message.error('Only support uploading one file!')
        return
      }
      const rawFile = files[0] // only use files[0]

      if (!this.isXml(rawFile)) {
        this.$message.error('Only supports upload .xml suffix files')
        return false
      }
      this.upload(rawFile)
      e.stopPropagation()
      e.preventDefault()
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },
    handleUpload() {
      this.$refs['xml-upload-input'].click()
    },
    handleClick(e) {
      const files = e.target.files
      const rawFile = files[0] // only use files[0]
      if (!rawFile) return
      this.upload(rawFile)
    },
    upload(rawFile) {
      this.$refs['xml-upload-input'].value = null // fix can't select the same excel

      if (!this.beforeUpload) {
        this.readerData(rawFile)
        return
      }
      const before = this.beforeUpload(rawFile)
      if (before) {
        this.readerData(rawFile)
      }
    },
    readerData(rawFile) {
      this.loading = true
      // this.$emit('table-loading', true)
      this.$emit('input', true)
      var that = this
      return new Promise(() => {
        const reader = new FileReader()
        reader.onload = function() {
          that.generateData(this.result)// 输出结果
          that.loading = false
          // that.$emit('table-loading', false)
          that.$emit('input', false)
        }
        // reader.readAsArrayBuffer(rawFile)
        // 换一种格式读

        reader.readAsText(rawFile)
      })
    },
    isXml(file) {
      return /\.(xml)$/.test(file.name)
    }
  }
}
</script>

<style scoped>
.xml-upload-input{
  display: none;
  z-index: -9999;
}
.drop{
  border: 2px dashed #bbb;
  width: 600px;
  height: 160px;
  line-height: 160px;
  margin: 0 auto;
  font-size: 24px;
  border-radius: 5px;
  text-align: center;
  color: #bbb;
  position: relative;
}
</style>
